package cn.edu.zafu.bigdata.lb;

import java.io.*;
import java.util.Scanner;

/**
 * @Author: LiuBo
 */
public class AppendAndReadFile {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的学号：");
        String studentId = scanner.nextLine();
        System.out.println("请输入您想要追加的文本：");
        String content = scanner.nextLine();

        String fileName = "files/" + studentId + ".txt";

        // 确保目录存在
        File directory = new File("files");
        if (!directory.exists()) {
            boolean isDirectoryCreated = directory.mkdirs();
            if (!isDirectoryCreated) {
                System.err.println("无法创建目录 'files'");
                scanner.close(); // 关闭scanner
                return; // 如果目录创建失败，则退出程序
            }
        }

        appendToFile(fileName, content);
        System.out.println("文件内容如下：");
        readFile(fileName);

        scanner.close(); // 关闭scanner
    }

    private static void appendToFile(String fileName, String content) {
        try (FileWriter writer = new FileWriter(fileName, true)) {
            writer.write(content);
            System.out.println("文本已成功追加到文件 " + fileName);
        } catch (IOException e) {
            System.err.println("追加文件时发生错误：" + e.getMessage());
        }
    }

    private static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("文件未找到：" + e.getMessage());
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
        }
    }
}